<template>
  <el-menu
    :default-active="activeMenu"
    mode="horizontal"
    @select="handleSelect"
    :ellipsis="false"
  >
  </el-menu>
</template>

<script setup>
import { constantRoutes } from "@/router";
import { isHttp } from "@/utils/validate";
import useAppStore from "@/store/modules/app";
import useSettingsStore from "@/store/modules/settings";
import usePermissionStore from "@/store/modules/permission";

import rygl from "@/assets/layout/人员管理.png";
import rwgl from "@/assets/layout/任务管理.png";
import yjcz from "@/assets/layout/应急处置.png";
import wdsp from "@/assets/layout/我的审批.png";
import dagl from "@/assets/layout/档案管理.png";
import xtsz from "@/assets/layout/系统设置.png";
import ywsjfx from "@/assets/layout/运维数据分析.png";
import ywkh from "@/assets/layout/运维考核.png";
import sy from "@/assets/layout/首页.png";

// 隐藏侧边栏路由
const hideList = ["/index/index", "/user/profile"];

const activeMenu = computed(() => {
  const path = route.path;
  let activePath = path;
  if (path !== undefined && path.lastIndexOf("/") > 0 && hideList.indexOf(path) === -1) {
    const tmpPath = path.substring(1, path.length);
    activePath = "/" + tmpPath.substring(0, tmpPath.indexOf("/"));
    if (!route.meta.link) {
      appStore.toggleSideBarHide(false);
    }
  } else if (!route.children) {
    activePath = path;
    appStore.toggleSideBarHide(true);
  }
  activeRoutes(activePath);
  return activePath;
});


function handleSelect(key, keyPath) {
  currentIndex.value = key;
  const route = routers.value.find((item) => item.path === key);
  if (isHttp(key)) {
    // http(s):// 路径新窗口打开
    window.open(key, "_blank");
  } else if (!route || !route.children) {
    // 没有子路由路径内部打开
    const routeMenu = childrenMenus.value.find((item) => item.path === key);
    if (routeMenu && routeMenu.query) {
      let query = JSON.parse(routeMenu.query);
      router.push({ path: key, query: query });
    } else {
      router.push({ path: key });
    }
    appStore.toggleSideBarHide(true);
  } else {
    // 显示左侧联动菜单
    activeRoutes(key);
    appStore.toggleSideBarHide(false);
    function getNextPath(route) {
      if (!route.children || route.children.length === 0) return "";

      const childPath = route.children[0].path;
      return (
        childPath +
        (route.children[0].children && route.children[0].children.length > 0
          ? "/" + getNextPath(route.children[0])
          : "")
      );
    }

    const path = getNextPath(route);
    router.push({ path });
  }
}


function activeRoutes(key) {
  let routes = [];
  if (childrenMenus.value && childrenMenus.value.length > 0) {
    childrenMenus.value.map((item) => {
      if (key == item.parentPath || (key == "/index" && "" == item.path)) {
        routes.push(item);
      }
    });
  }
  if (routes.length > 0) {
    permissionStore.setSidebarRouters(routes);
  } else {
    appStore.toggleSideBarHide(true);
  }
  return routes;
}
</script>

<style lang="scss" scoped></style>
